package pl.jtb.ctl.tabory.ui.se.ui;

import java.util.Date;

import org.apache.log4j.Logger;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DateTime;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;

import pl.jtb.ctl.tabory.dao.api.services.IUserRoleService;
import pl.jtb.ctl.tabory.dao.data.sl.UserRoleSL;
import pl.jtb.ctl.tabory.dao.data.vo.UserRoleVO;
import pl.jtb.ctl.tabory.dao.data.vo.UserVO;
import pl.jtb.ctl.tabory.dao.impl.mybatis.servicemanager.ServiceManager;
import pl.jtb.ctl.tabory.ui.editors.AbstractDetailSectionPart;
import pl.jtb.ctl.tabory.ui.editors.EditorStateSL;
import pl.jtb.ctl.tabory.ui.se.osgi.Activator;
import pl.jtb.ctl.tabory.ui.se.selection.UserSelection;
import pl.jtb.ctl.tabory.ui.selection.ISelectionListener;
import pl.jtb.ctl.tabory.ui.util.CommonDateUtils;

public class SecurityDetailSectionPart extends AbstractDetailSectionPart<UserSelection> {

    private final static Logger logger = Logger.getLogger(SecurityDetailSectionPart.class);

    private Text userName;
    private Text userLogon;
    private Text userPass;
    private Combo userRoleCombo;
    private DateTime validFromControl;
    private DateTime validUntilControl;
    private Button isActiveButton;

    private Composite client;

    public SecurityDetailSectionPart(Composite parent, FormToolkit toolkit, int style, String sectionName) {
        super(parent, toolkit, style, sectionName);
    }

    @Override
    public UserSelection getSelection() {
        logger.debug("Retriving selection.");
        try {
            UserVO selectedUser = selection.getSelectedUser();
            if (selectedUser == null) {
                selectedUser = new UserVO();
            }
            selectedUser.setActive(isActiveButton.getSelection());
            selectedUser.setUserLogon(userLogon.getText());
            selectedUser.setUserName(userName.getText());
            selectedUser.setUserPass(userPass.getText());
            IUserRoleService userRoleService = ServiceManager.getInstance().getUserRoleService();
            UserRoleVO userRole = userRoleService.getUserRole(Long.valueOf(userRoleCombo.getSelectionIndex()));
            selectedUser.setUserRoleVO(userRole);
            if (!userRole.getId().equals(UserRoleSL.ADMINISTRATOR.getId())) {
                Date dateValidFrom = CommonDateUtils.getDate(validFromControl.getYear(), validFromControl.getMonth(), validFromControl.getDay());
                selectedUser.setDateValidFrom(dateValidFrom);
                Date dateValidUntil = CommonDateUtils.getDate(validUntilControl.getYear(), validUntilControl.getMonth(), validUntilControl.getDay());
                selectedUser.setDateValidUntil(dateValidUntil);
            } else {
                selectedUser.setDateValidFrom(null);
                selectedUser.setDateValidUntil(null);
            }
            selection.setSelectedUser(selectedUser);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return selection;
    }

    @Override
    public void setSelection(UserSelection selection) {
        logger.debug("Setting selection: " + selection.toString());
        this.selection = selection;
        EditorStateSL editorStateSL = selection.getEditorStateSL();
        if (editorStateSL.equals(EditorStateSL.NEW)) {
            client.setVisible(true);
            setEnabled(true);
            userLogon.setText("");
            userName.setText("");
            userPass.setText("");
            userRoleCombo.select(0);
            setValidFieldsEnabled();
            userName.setFocus();
        } else if (editorStateSL.equals(EditorStateSL.CLEAN)) {
            fillEditorValues();
            setEnabled(false);
        } else if (editorStateSL.equals(EditorStateSL.EDITING)) {
            fillEditorValues();
            setEnabled(true);
            setValidFieldsEnabled();
            userName.setFocus();
        }
    }

    private void fillEditorValues() {
        UserVO selectedUser = selection.getSelectedUser();
        if (selectedUser != null) {
            client.setVisible(true);
            userLogon.setText(selectedUser.getUserLogon());
            userName.setText(selectedUser.getUserName());
            userPass.setText(selectedUser.getUserPass());
            Date dateValidFrom = selectedUser.getDateValidFrom();
            validFromControl.setDate(CommonDateUtils.getYear(dateValidFrom), CommonDateUtils.getMonth(dateValidFrom), CommonDateUtils.getDay(dateValidFrom));
            Date dateValidUntil = selectedUser.getDateValidUntil();
            validUntilControl.setDate(CommonDateUtils.getYear(dateValidUntil), CommonDateUtils.getMonth(dateValidUntil), CommonDateUtils.getDay(dateValidUntil));
            isActiveButton.setSelection(selectedUser.isActive());
            userRoleCombo.select((selectedUser.getUserRoleVO().getId().intValue()));
        } else {
            client.setVisible(false);
        }
    }

    @Override
    public void addSelectionListener(ISelectionListener<UserSelection> listner) {
    }

    @Override
    public void removeSelectionListener(ISelectionListener<UserSelection> listner) {
    }

    @Override
    protected void initGui(Section parentSection, FormToolkit toolkit) {
        logger.debug("Initializing GUI.");

        GridLayoutFactory.fillDefaults().numColumns(1).applyTo(parentSection);
        client = toolkit.createComposite(parentSection);
        GridLayoutFactory.fillDefaults().numColumns(2).margins(3, 3).applyTo(client);
        parentSection.setClient(client);

        Label labelUserName = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.username"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelUserName);

        userName = toolkit.createText(client, null);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(120, SWT.DEFAULT).applyTo(userName);

        Label labelUserLogon = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.userlogon"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelUserLogon);

        userLogon = toolkit.createText(client, null);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(120, SWT.DEFAULT).applyTo(userLogon);

        Label labelUserPass = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.pass"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelUserPass);

        userPass = toolkit.createText(client, null, SWT.PASSWORD);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(120, SWT.DEFAULT).applyTo(userPass);

        Label labelUserRole = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.userrole"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelUserRole);

        userRoleCombo = new Combo(client, SWT.DROP_DOWN | SWT.READ_ONLY);
        for (UserRoleSL userRole : UserRoleSL.values()) {
            userRoleCombo.add(userRole.getName());
        }
        toolkit.adapt(userRoleCombo);
        toolkit.paintBordersFor(userRoleCombo);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(120, SWT.DEFAULT).applyTo(userRoleCombo);

        Label labelValidFrom = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.validfrom"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelValidFrom);

        validFromControl = new DateTime(client, SWT.DATE | SWT.DROP_DOWN | SWT.BORDER);
        toolkit.adapt(validFromControl);
        toolkit.paintBordersFor(validFromControl);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(80, SWT.DEFAULT).applyTo(validFromControl);

        Label labelValidUntil = toolkit.createLabel(client, Activator.getMessage("editor.detail.label.validuntil"));
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).applyTo(labelValidUntil);

        validUntilControl = new DateTime(client, SWT.DATE | SWT.DROP_DOWN | SWT.BORDER);
        toolkit.adapt(validUntilControl);
        toolkit.paintBordersFor(validUntilControl);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(80, SWT.DEFAULT).applyTo(validUntilControl);

        isActiveButton = toolkit.createButton(client, Activator.getMessage("editor.detail.label.active"), SWT.CHECK);
        GridDataFactory.fillDefaults().align(SWT.FILL, SWT.CENTER).grab(false, false).hint(80, SWT.DEFAULT).span(1, 2).applyTo(isActiveButton);

        toolkit.adapt(client);
        toolkit.paintBordersFor(client);
        client.setVisible(false);
    }

    @Override
    protected void postInitGui(Section parentSection, FormToolkit toolkit) {
    }

    @Override
    protected void initActions() {
        userRoleCombo.addSelectionListener(new SelectionAdapter() {

            @Override
            public void widgetSelected(SelectionEvent e) {
                setValidFieldsEnabled();
            }
        });
    }

    private void setValidFieldsEnabled() {
        int selectionIndex = userRoleCombo.getSelectionIndex();
        if (selectionIndex == -1) {
            return;
        }
        if (selectionIndex == UserRoleSL.ADMINISTRATOR.getId()) {
            validFromControl.setEnabled(false);
            validUntilControl.setEnabled(false);
        } else {
            validFromControl.setEnabled(true);
            validUntilControl.setEnabled(true);
        }
    }

    @Override
    public void setEnabled(boolean isEnabled) {
        userLogon.setEnabled(isEnabled);
        userName.setEnabled(isEnabled);
        userPass.setEnabled(isEnabled);
        userRoleCombo.setEnabled(isEnabled);
        validFromControl.setEnabled(isEnabled);
        validUntilControl.setEnabled(isEnabled);
        isActiveButton.setEnabled(isEnabled);
    }

}
